import arrow

from bson import ObjectId

from app.db import redis
from app.db.models.notifications import Notifications
from app.errors import ParameterError


def create_system_notification(uid_list, title, msg):
    uid_list = [ObjectId(item) for item in uid_list if not isinstance(item, ObjectId)]

    Notifications(
        category='告警通知',
        from_='系统',
        to=uid_list,
        level='warning',
        datetime=arrow.utcnow().datetime,
        title=title,
        message=msg
    ).save()


class CodeVerified(object):

    @staticmethod
    def phone_verified(uid, address, code):
        key = f"scanv_verified_code_{str(uid)}_{address}"
        if not (value := redis.get(key)):
            raise ParameterError(msg='电话验证码不匹配')
        if str(code) != value.decode():
            raise ParameterError(msg='电话验证码不匹配')
        else:
            redis.delete(key)
            return True

    @staticmethod
    def email_verified(uid, address, code):
        key = f"scanv_verified_code_{str(uid)}_{address}"
        if not (value := redis.get(key)):
            raise ParameterError(msg='邮件验证码不匹配')
        if str(code) != value.decode():
            raise ParameterError(msg='邮件验证码不匹配')
        else:
            redis.delete(key)
            return True

    @staticmethod
    def save_code(uid, address, code):
        if redis.get(f"scanv_verified_code_{str(uid)}_{address}"):
            raise ParameterError(msg='5分钟内不要重复请求')
        redis.set(f"scanv_verified_code_{str(uid)}_{address}", code, ex=5 * 60)

    @staticmethod
    def check_code_time(uid, address):
        if redis.get(f"scanv_verified_code_{str(uid)}_{address}"):
            raise ParameterError(msg='5分钟内不要重复请求')
